document.write('<script type="text/javascript" src="../resources/mxGraph/js/mxNote.js"></script>');
var needRemoveStyleNote = [];

function onInit(editor) {
    mxConnectionHandler.prototype.connectImage = new mxImage('../resources/mxGraph/images/connector.gif', 16, 16);
    mxVertexHandler.prototype.rotationEnabled = true;
    mxGraphHandler.prototype.guidesEnabled = true;
    mxGraph.prototype.htmlLabels = false;
    mxGuide.prototype.isEnabledForEvent = function (evt) {
        return !mxEvent.isAltDown(evt);
    };
    mxEdgeHandler.prototype.snapToTerminals = true;

    // label 更改事件
    editor.graph.labelChanged = function (cell, value, evt) {
        this.model.beginUpdate();
        try {
            var old = cell.value;
            if (old.nodeName == 'Connector') {
                // 连线上的数值去掉 % 号
                value = value.replace(/%/g, "");
            }
            this.cellLabelChanged(cell, value, this.isAutoSizeCell(cell));
            this.fireEvent(new mxEventObject(mxEvent.LABEL_CHANGED,
                'cell', cell, 'value', value, 'old', old, 'event', evt));
        } finally {
            this.model.endUpdate();
        }
        return cell;
    };


    var funct = function (editor) {
        if (needRemoveStyleNote.length > 0) {
            for (var i = 0; i < needRemoveStyleNote.length; i++) {
                var cell = geditor.graph.getModel().getCell(needRemoveStyleNote[i]);
                if (cell != null) {
                    delOverlay(needRemoveStyleNote[i]);
                }
            }
        }
        needRemoveStyleNote = [];
        var id = $("#imageId").val();
        if (id == null) {
            id = "";
        }
        var enc = new mxCodec();
        var node = enc.encode(editor.graph.getModel());
        var xml = encodeURIComponent(mxUtils.getPrettyXml(node));//用来页面展示的xml

        var graph = editor.graph;
        var scale = 1;
        var b = 1;
        var imgExport = new mxImageExport();
        var bounds = graph.getGraphBounds();
        var vs = graph.view.scale;
        // New image export
        var xmlDoc = mxUtils.createXmlDocument();
        var root = xmlDoc.createElement('output');
        xmlDoc.appendChild(root);

        // Renders graph. Offset will be multiplied with state's scale when painting state.
        var xmlCanvas = new mxXmlCanvas2D(root);
        xmlCanvas.translate(Math.floor((b / scale - bounds.x) / vs), Math.floor((b / scale - bounds.y) / vs));
        xmlCanvas.scale(scale / vs);

        imgExport.drawState(graph.getView().getState(graph.model.root), xmlCanvas);

        // Puts request data together
        var w = Math.ceil(bounds.width * scale / vs + 2 * b);
        var h = Math.ceil(bounds.height * scale / vs + 2 * b);
        //alert(mxUtils.getXml(root));
        //layer.msg(mxUtils.getXml(root));
        var imageXML = encodeURIComponent(mxUtils.getXml(root));//用来生成图片的xml
        if (w > 0 && h > 0) {

            $.ajax({
                url: baseUrl + '/profile/saveProfileXML',
                type: 'post', //数据发送方式
                dataType: 'json', //接受数据格式
                async: false,
                data: {
                    "id": id, "xml": xml, "w": w, "h": h, "imageXML": imageXML, "pId": projectId, "type": type
                },
                success: function (data) {
                    if (data.code == '0') {
                        imageFlag = false;
                        nextFlag = false;
                    } else {
                        imageFlag = true;
                        nextFlag = true;
                    }
                    layer.msg(data.message, {time: 1000}, function () {
                        $("#imageId").val(data.data);
                        //alert("ID="+data.data);
                        if (data.code == '0') {
                            var errorData = eval(data.errorData);
                            for (var i = 0; i < errorData.length; i++) {
                                if ("0" == errorData[i].id) {
                                    layer.msg(errorData[i].name);
                                } else {
                                    addOverlay(errorData[i].id, errorData[i].name);
                                    needRemoveStyleNote.push(errorData[i].id);
                                }
                            }
                        } else {
                            //保存成功刷新表格
                            refreshTable();
                        }
                    });
                },
                error: function () {
                    layer.msg("系统错误");
                }
            });
        }
    };

    editor.addAction('save', funct);
    var exportImage = function (editor) {
        var graph = editor.graph;
        var scale = 1;
        var b = 1;
        var imgExport = new mxImageExport();
        var bounds = graph.getGraphBounds();
        var vs = graph.view.scale;

        // New image export
        var xmlDoc = mxUtils.createXmlDocument();
        var root = xmlDoc.createElement('output');
        xmlDoc.appendChild(root);

        // Renders graph. Offset will be multiplied with state's scale when painting state.
        var xmlCanvas = new mxXmlCanvas2D(root);
        xmlCanvas.translate(Math.floor((b / scale - bounds.x) / vs), Math.floor((b / scale - bounds.y) / vs));
        xmlCanvas.scale(scale / vs);

        imgExport.drawState(graph.getView().getState(graph.model.root), xmlCanvas);

        // Puts request data together
        var w = Math.ceil(bounds.width * scale / vs + 2 * b);
        var h = Math.ceil(bounds.height * scale / vs + 2 * b);
        var xml = encodeURIComponent(mxUtils.getXml(root));
        // Requests image if request is valid
        if (w > 0 && h > 0) {
            $("#w").val(w);
            $("#h").val(h);
            $("#imageXML").val(xml);
            $("#form").submit();
        }
    };

    editor.addAction('exportImage', exportImage);

    var page = document.getElementById("page");
    var fullScreen = function (editor) {
        document.body.style.height = '0px';
        var w = document.body.clientWidth;
        var h = document.body.clientHeight;
        page.style.position = 'fixed';
        page.style.width = '100%';
        page.style.height = h + 'px';
        page.style.top = '15px';
    };
    editor.addAction('fullScreen', fullScreen);

    var windows = function (editor) {
        document.body.style.height = '';
        page.style.position = '';
        page.style.width = '';
        page.style.height = '';
        page.style.top = '';
    };
    editor.addAction('windows', windows);

    if (a == null || a == "") {
        return;
    }
    var doc = mxUtils.parseXml(a);
    var dec = new mxCodec(doc);
    dec.decode(doc.documentElement, editor.graph.getModel());
    editor.modified = false;
}

//给物体添加报警
var addOverlay = function (id, state) {
    // 获取ID单元
    var cell = geditor.graph.getModel().getCell(id);
    // 修改有报警物体的样式
    //geditor.graph.setCellStyles(mxConstants.STYLE_FILLCOLOR, "#FF0000", [cell]);
    //geditor.graph.setCellStyles(mxConstants.STYLE_FONTCOLOR, "#FFFFFF", [cell]);
    // 添加告警
    geditor.graph.addCellOverlay(cell, createOverlay(geditor.graph.warningImage, '状态: ' + state));
};

// 创建告警信息
var createOverlay = function (image, tooltip) {
    //function mxCellOverlay(image,tooltip,align,verticalAlign,offset,cursor)
    //image图片，tooltip提示，align位置，verticalAlign竖直位置
    var overlay = new mxCellOverlay(image, tooltip);
    overlay.addListener(mxEvent.CLICK, function (sender, evt) {
        mxUtils.alert(tooltip);
    });
    return overlay;
};

// 移出报警
var delOverlay = function (id) {
    // 获取ID单元
    var cell = geditor.graph.getModel().getCell(id);
    // 修改有报警物体的样式
    //geditor.graph.setCellStyles(mxConstants.STYLE_FILLCOLOR, "#C3D9FF", [cell]);
    // geditor.graph.setCellStyles(mxConstants.STYLE_STROKECOLOR, "#6482B9", [cell]);
    //geditor.graph.setCellStyles(mxConstants.STYLE_FONTCOLOR, "black", [cell]);
    // 移除告警
    geditor.graph.removeCellOverlays(cell);
};



